package cn.neo.hhrpc.core.registry.hh;


import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * check health for registry center
 */
@Slf4j
public class HHHealthChecker {

    ScheduledExecutorService consumerExecutor = null;
    ScheduledExecutorService providerExecutor = null;

    public void start() {
        log.info(" ===>>> [HHRegistry] : start with health checker. ");
        consumerExecutor = Executors.newScheduledThreadPool(1);
        providerExecutor = Executors.newScheduledThreadPool(1);


    }


    public void stop() {
        log.info(" ===>>> [HHRegistry] : stop with health checker. ");
        gracefulShutdown(consumerExecutor);
        gracefulShutdown(providerExecutor);
    }

    public void consumerCheck(Callback callback) {
        consumerExecutor.scheduleAtFixedRate(() -> {
            try{
                callback.call();
            } catch (Exception e) {
                e.printStackTrace();
            }
        },1,5,TimeUnit.SECONDS);
    }

    public void providerCheck(Callback callback) {
        providerExecutor.scheduleAtFixedRate(() -> {
            try{
                callback.call();
            } catch (Exception e) {
                e.printStackTrace();
            }
        },5,5,TimeUnit.SECONDS);
    }


    /**
     * 优雅停机
     *
     * @param executorService
     */
    private void gracefulShutdown(ScheduledExecutorService executorService) {
        executorService.shutdown();
        try {
            // 等待1秒后判断是否停止，如果没有停下来，强制停止
            executorService.awaitTermination(1000, TimeUnit.MILLISECONDS);
            if (!executorService.isTerminated()) {
                executorService.shutdown();
            }

        } catch (InterruptedException e) {
            // ingore
        }
    }

    public interface Callback {
        void call() throws Exception;
    }
}
